package com.example.tts.demo;

import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.exceptions.MaryConfigurationException;
import marytts.exceptions.SynthesisException;
import marytts.modules.synthesis.Voice;
import marytts.util.data.audio.AudioPlayer;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import java.io.Closeable;
import java.io.IOException;

public class HelloWorld {

    public static void main(String[] args) {
        try {
            TTS tts = new TTS();
            tts
                    .speak("Hello World.")
                    .speak("This is the sound of Mary Tee Tee Ess.")
                    .speak("This is the voice of the machines taking over.")
                    .speak("We are The Borg. Resistance is fu-tile.");
        } catch (MaryConfigurationException | IOException | SynthesisException | LineUnavailableException | InterruptedException e) {
            System.err.println("MaryTTS doesn't seem to work on this machine.");
        } finally {
            // Regardless of TTS, we must full-fil our contractual obligation of printing "Hello World"
            System.out.println("Hello World");
        }
    }

    public static class TTS implements Closeable {

        private final MaryInterface mary;

        public TTS() throws MaryConfigurationException {
            mary = new LocalMaryInterface();
            // Available voices
            Voice.getAvailableVoices().stream().forEach(System.out::println);
//            mary.setVoice("cmu-slt-hsmm");
            mary.setVoice("dfki-spike-hsmm");
//            mary.setVoice("dfki-prudence-hsmm");
//            mary.setVoice("dfki-poppy-hsmm");
//            mary.setAudioEffects("F0Scale(f0Scale:0.0)+Robot(amount:75.0)+Whisper(amount:35)");
            mary.setAudioEffects("");
        }

        public TTS speak(String text) throws SynthesisException, LineUnavailableException, IOException, InterruptedException {
            AudioInputStream audioInputStream = mary.generateAudio(text);
            // Player is a thread(threads can only run one time) so it can be
            // used has to be initiated every time
//            AudioPlayer player = new AudioPlayer(audioInputStream, event -> {
//            });
            AudioPlayer player = new AudioPlayer();
            player.setAudio(audioInputStream);
            player.setDaemon(true);
            player.start();
            while (player.isAlive()) {
                Thread.sleep(100);
            }
            return this;
        }

        @Override
        public void close() throws IOException {
        }

    }


}
